package com.sw.chinesewriteboard.copybook;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.SeekBar;

import androidx.annotation.DrawableRes;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sw.chinesewriteboard.R;
import com.sw.chinesewriteboard.adapter.GeziAdapter;
import com.sw.chinesewriteboard.adapter.ZitiAdapter;
import com.sw.chinesewriteboard.config.ChineseDataConfig;
import com.sw.chinesewriteboard.databinding.ViewBottomNavigationBinding;
import com.sw.chinesewriteboard.model.MyColor;
import com.sw.chinesewriteboard.model.MyData;
import com.sw.chinesewriteboard.model.MyTypeface;
import com.sw.chinesewriteboard.operation.ChineseDataOperate;
import com.sw.chinesewriteboard.operation.EnglishDataOperate;
import com.sw.chinesewriteboard.operation.TypefaceOperate;
import com.sw.chinesewriteboard.utils.KeyBoardUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.PatternSyntaxException;

public class BottomContainerView extends ConstraintLayout {

    private ViewBottomNavigationBinding binding;

    private BottomContainerCallback bottomContainerCallback;

    private CopybookActivity activity;
    private List<String> listContent = new ArrayList<>();
    private MyData data;
    public boolean isZh;

    private int kbhSum = 0; //空白行行数

    TextWatcher zhTextWatcher;
    TextWatcher enTextWatcher;

    public BottomContainerView(Context context) {
        this(context, null);
    }

    public BottomContainerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomContainerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
//        init();
    }

    private void init() {
        binding = ViewBottomNavigationBinding.inflate(LayoutInflater.from(getContext()), this, true);
        binding.vbnBottomNavigation.setOnNavigationItemSelectedListener(item -> {
            setContainerInvisible();
            if (item.getItemId() == R.id.neirong) {
                binding.vbnContainerNeirong.setVisibility(VISIBLE);
            } else if (item.getItemId() == R.id.ziti) {
                binding.vbnContainerZiti.setVisibility(VISIBLE);
            } else if (item.getItemId() == R.id.gezi) {
                binding.vbnContainerGezi.setVisibility(VISIBLE);
            }
            return true;
        });

        binding.vbnNrEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                binding.vbnBottomNavigation.setVisibility(hasFocus ? GONE : VISIBLE);
                binding.vbnNrSure.setVisibility(hasFocus ? VISIBLE : GONE);
                binding.vbnNrCancel.setVisibility(hasFocus ? VISIBLE : GONE);
            }
        });

//        zhTextWatcher = new LimitInputTextWatcher(binding.vbnNrEdit, "[^\u4E00-\u9FA5 ]");
//        zhTextWatcher = new LimitInputTextWatcher(binding.vbnNrEdit, "[\\u4E00-\\u9FA5 ]+");
//        enTextWatcher = new LimitInputTextWatcher(binding.vbnNrEdit, "[^a-zA-Z ]");

        zhTextWatcher = new TextWatcher() {
            String str;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                EditText editText = binding.vbnNrEdit;
                String str = editable.toString();
                String inputStr = stringFilterZh(str);
                editText.removeTextChangedListener(this);
                // et.setText方法可能会引起键盘变化,所以用editable.replace来显示内容
                editable.replace(0, editable.length(), inputStr);
                editText.addTextChangedListener(this);
            }
        };

        enTextWatcher = new TextWatcher() {
            String str;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                EditText editText = binding.vbnNrEdit;
                String str = editable.toString();
                String inputStr = stringFilterEn(str);
                editText.removeTextChangedListener(this);
                // et.setText方法可能会引起键盘变化,所以用editable.replace来显示内容
                editable.replace(0, editable.length(), inputStr);
                editText.addTextChangedListener(this);
            }
        };
        binding.vbnNrEdit.addTextChangedListener(isZh ? zhTextWatcher : enTextWatcher);

        binding.vbnNrSure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = binding.vbnNrEdit.getText().toString();
                if (bottomContainerCallback != null) {
                    bottomContainerCallback.editCallback(content);
                }
                listContent.clear();
                listContent.add(content);
                activity.refreshCopyBookView();
                binding.vbnNrEdit.clearFocus();
                KeyBoardUtils.hideKeyBoard(activity);
            }
        });

        binding.vbnNrCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.vbnNrEdit.clearFocus();
                KeyBoardUtils.hideKeyBoard(activity);
            }
        });

        ZitiAdapter zitiAdapter = new ZitiAdapter(isZh ? new TypefaceOperate(getContext()).initZhTypeface() : new TypefaceOperate(getContext()).initEnTypeface(), new ZitiAdapter.ItemClickListener() {
            @Override
            public void onItemClick(MyTypeface myTypeface) {
                if (bottomContainerCallback != null)
                    bottomContainerCallback.zitiItemClick(myTypeface);
                data.setMyTypeface(myTypeface);
                activity.refreshCopyBookView();
            }
        });
        binding.vbnZitiRv.setAdapter(zitiAdapter);
        binding.vbnZitiRv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));

        binding.vbnZitiSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {


            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int textSize = 0;
                int progress = seekBar.getProgress();
                if (progress < 25) {
                    progress = 0;
                    seekBar.setProgress(progress);
                    textSize = 48;
                    changeTextSize(textSize);
                } else if (progress < 50) {
                    progress = 33;
                    seekBar.setProgress(progress);
                    textSize = 52;
                    changeTextSize(textSize);
                } else if (progress < 75) {
                    progress = 66;
                    seekBar.setProgress(progress);
                    textSize = 56;
                    changeTextSize(textSize);
                } else {
                    progress = 100;
                    seekBar.setProgress(progress);
                    textSize = 60;
                    changeTextSize(textSize);
                }
            }
        });

        binding.vbnZitiSeekbarAlpha.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                float alpha = 0;
                String text = "20%";
                int progress = seekBar.getProgress();
                if (progress < 25) {
                    progress = 0;
                    seekBar.setProgress(progress);
                    alpha = 0.2f;
                    text = "20%";
                    changeTextAlpha(alpha);
                } else if (progress < 50) {
                    progress = 25;
                    seekBar.setProgress(progress);
                    alpha = 0.4f;
                    text = "40%";
                    changeTextAlpha(alpha);
                } else if (progress < 75) {
                    progress = 50;
                    seekBar.setProgress(progress);
                    alpha = 0.6f;
                    text = "60%";
                    changeTextAlpha(alpha);
                } else if (progress < 100) {
                    progress = 75;
                    seekBar.setProgress(progress);
                    alpha = 0.8f;
                    text = "80%";
                    changeTextAlpha(alpha);
                }else {
                    progress = 100;
                    seekBar.setProgress(progress);
                    alpha = 1.0f;
                    text = "100%";
                    changeTextAlpha(alpha);
                }
                binding.vbnZitiTvAlpha.setText(text);
            }
        });

        List<Integer> geziList = new ArrayList<>();
        if (isZh) {
            geziList.add(R.mipmap.aa_biaoge1);
            geziList.add(R.mipmap.aa_biaoge2);
            geziList.add(R.mipmap.aa_biaoge3);
            geziList.add(R.mipmap.aa_biaoge4);
            geziList.add(R.mipmap.aa_biaoge5);
            geziList.add(R.mipmap.aa_biaoge6);
        } else {
            geziList.add(R.mipmap.aa_biao_9);
            geziList.add(R.mipmap.aa_biao_10);
            geziList.add(R.mipmap.aa_biao_11);
        }

        GeziAdapter geziAdapter = new GeziAdapter(geziList, new GeziAdapter.ItemClickListener() {

            @Override
            public void onItemClick(int drwId) {
                if (bottomContainerCallback != null)
                    bottomContainerCallback.geziItemClick(drwId);
                data.setDrwId(drwId);
                activity.refreshCopyBookView();
            }
        });
        binding.vbnGeziRv.setAdapter(geziAdapter);
        binding.vbnGeziRv.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));

        binding.vbnGeziKuandu13.setOnClickListener(kuanduListener);
        binding.vbnGeziKuandu15.setOnClickListener(kuanduListener);
        binding.vbnGeziKuandu17.setOnClickListener(kuanduListener);

        binding.vbnGeziYanseRed.setOnClickListener(yanseListener);
        binding.vbnGeziYanseGreen.setOnClickListener(yanseListener);
        binding.vbnGeziYanseBlue.setOnClickListener(yanseListener);
        binding.vbnGeziYanseBlack.setOnClickListener(yanseListener);

        binding.vbnGeziBtnJia.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (kbhSum < 3) {
                    binding.vbnGeziTvKongbaihang.setText(++kbhSum + "");
                    if (isZh) {
                        ChineseDataOperate.setRowEmpty(kbhSum);
                    } else {
                        EnglishDataOperate.setRowEmpty(kbhSum);
                    }
                    activity.refreshCopyBookView();
                } else {
//                    Toast.makeText(getContext(), "空白行最多三行~", Toast.LENGTH_SHORT).show();
                }
            }
        });

        binding.vbnGeziBtnJian.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (kbhSum > 0) {
                    binding.vbnGeziTvKongbaihang.setText(--kbhSum + "");
                    if (isZh) {
                        ChineseDataOperate.setRowEmpty(kbhSum);
                    } else {
                        EnglishDataOperate.setRowEmpty(kbhSum);
                    }
                    activity.refreshCopyBookView();
                } else {
//                    Toast.makeText(getContext(), "空白行最多三行~", Toast.LENGTH_SHORT).show();
                }
            }
        });

        binding.vbnGeziRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.vbn_gezi_rb_all) {
                    if (isZh) {
                        ChineseDataOperate.setDivison(1f);
                    } else {
                        EnglishDataOperate.setDivison(1f);
                    }
                } else if (checkedId == R.id.vbn_gezi_rb_half) {
                    if (isZh) {
                        ChineseDataOperate.setDivison(0.5f);
                    } else {
                        EnglishDataOperate.setDivison(0.5f);
                    }
                } else if (checkedId == R.id.vbn_gezi_rb_none) {
                    if (isZh) {
                        ChineseDataOperate.setDivison(0f);
                    } else {
                        EnglishDataOperate.setDivison(0f);
                    }
                }
                activity.refreshCopyBookView();
            }
        });
    }

    public static String stringFilterZh(String str) throws PatternSyntaxException {
        // 只允许字母、和空格和汉字
        String regEx = "[\\u4E00-\\u9FA5 ]+";
        return str != null ? (str.matches(regEx) ? str : "") : "";
    }

    public static String stringFilterEn(String str) throws PatternSyntaxException {
        // 只允许字母、和空格和汉字
        String regEx = "[a-zA-Z ]+";
        return str != null ? (str.matches(regEx) ? str : "") : "";
    }

    private void changeTextSize(final int textSize) {
        if (bottomContainerCallback != null)
            bottomContainerCallback.zitiSizeChange(textSize);
        data.setTextSize(textSize);
        activity.refreshCopyBookView();
    }

    private void changeTextAlpha(float alpha) {
        data.setAlpha(alpha);
        activity.refreshCopyBookView();
    }

    private final View.OnClickListener kuanduListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int gridWidth = 13;
            int id = v.getId();
            if (id == R.id.vbn_gezi_kuandu_13) {
                gridWidth = 13;
            } else if (id == R.id.vbn_gezi_kuandu_15) {
                gridWidth = 15;
            } else if (id == R.id.vbn_gezi_kuandu_17) {
                gridWidth = 17;
            }
            if (bottomContainerCallback != null)
                bottomContainerCallback.geziKuanduClick(gridWidth);
            ChineseDataConfig.setGridWidth(gridWidth, ((ZhCopybookActivity) activity).isPinyinEnabled());
            activity.refreshCopyBookView();
        }
    };

    private final View.OnClickListener yanseListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyColor myColor = new MyColor("", R.color.colorRed);
            int id = v.getId();
            if (id == R.id.vbn_gezi_yanse_red) {
                myColor.setColor(activity.getResources().getColor(R.color.colorRed));
            } else if (id == R.id.vbn_gezi_yanse_green) {
                myColor.setColor(activity.getResources().getColor(R.color.colorGreen));
            } else if (id == R.id.vbn_gezi_yanse_blue) {
                myColor.setColor(activity.getResources().getColor(R.color.colorBlue));
            } else if (id == R.id.vbn_gezi_yanse_black) {
                myColor.setColor(activity.getResources().getColor(R.color.colorBlack));
            }
            if (bottomContainerCallback != null)
                bottomContainerCallback.geziYanseClick(myColor);
            data.setBackgroundColor(myColor);
            data.setFontColor(myColor);
            activity.refreshCopyBookView();
        }
    };

    public void removeTextWatcher() {
        binding.vbnNrEdit.removeTextChangedListener(zhTextWatcher);
        binding.vbnNrEdit.removeTextChangedListener(enTextWatcher);
    }

    public void initEnvironment(CopybookActivity activity, boolean isZh) {
        this.activity = activity;
        listContent = activity.getListContent();
        data = activity.getData();
        this.isZh = isZh;

        init();
    }

    public void setContainerInvisible() {
        binding.vbnContainerNeirong.setVisibility(GONE);
        binding.vbnContainerZiti.setVisibility(GONE);
        binding.vbnContainerGezi.setVisibility(GONE);
    }

    public void setContantHint(String hint) {
        binding.vbnNrEdit.setHint(hint);
    }

    public void setBottomContainerCallback(BottomContainerCallback bottomContainerCallback) {
        this.bottomContainerCallback = bottomContainerCallback;
    }

    public interface BottomContainerCallback {
        // 内容选择
        void editCallback(String content);

        // 字体选择
        void zitiItemClick(MyTypeface myTypeface);

        // 字体大小
        void zitiSizeChange(int progress);

        void geziItemClick(@DrawableRes int drwId);

        void geziKuanduClick(int gridWidth);

        void geziYanseClick(MyColor myColor);
    }
}
